﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using Microsoft.SharePoint;

namespace RoketSolutions.SP2010.Infrostructure.Common
{
    public static class Utility
    {
        public static string CombineUrlParts(string baseUrl, string relativeUrl)
        {
            if (baseUrl.Length == 0)
                return relativeUrl;

            if (relativeUrl.Length == 0)
                return baseUrl;

            return string.Format("{0}/{1}", baseUrl.TrimEnd(new[] { '/', '\\' }), relativeUrl.TrimStart(new[] { '/', '\\' }));
        }

        public static void CreateSPView(SPWeb web, string listName, List<string> fields, string viewName, string strQuery, bool makeDefault)
        {
            CreateSPView(web, listName, fields, viewName, strQuery, makeDefault, -1);
        }

        public static void CreateSPView(SPWeb web, string listName, List<string> fields, string viewName, string strQuery, bool makeDefault, int itemsLimit)
        {
            try
            {
                var list = web.Lists.TryGetList(listName);
                var oViewCollection = list.Views;
                var viewFields = new StringCollection();
                foreach (var field in fields)
                {
                    viewFields.Add(field);
                }
                try
                {
                    var view = oViewCollection[viewName];
                    list.Views.Delete(view.ID);
                }
                catch { }
                finally
                {
                    list.Update();
                    web.Update();
                    var listView = oViewCollection.Add(viewName, viewFields, strQuery, 100, true, makeDefault);
                    if (itemsLimit != -1)
                    {
                        listView.RowLimit = (uint)itemsLimit;
                        listView.Update();
                    }
                }
                list.Update();
            }
            catch (Exception e)
            {
                // todo: add error logging
                //SpLogger.Log.Error("Failed to create view.", e);
            }
        }
    }
}